package pers.yefeng.base;


import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

@Data
public class View<T> implements Serializable {

    private static final long serialVersionUID = 4031964063551764134L;

    private Integer code;
    private String msg = "";
    private String str = "";
    private T data;


    /**
     * 统一返回成功
     *
     * @param msg 成功描述 可以为空
     */
    public static <T> View<T> success(String msg) {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.SUCCESS.getCode());
        view.setMsg(StringUtils.isNotBlank(msg) ? msg : BaseCodeEnum.SUCCESS.getMsg());
        return view;
    }

    public static <T> View<T> success() {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.SUCCESS.getCode());
        view.setMsg(BaseCodeEnum.SUCCESS.getMsg());
        return view;
    }

    /**
     * 统一返回成功
     *
     * @param msg  成功描述 可以为空
     * @param data 值
     */
    public static <T> View<T> success(String msg, T data) {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.SUCCESS.getCode());
        view.setMsg(StringUtils.isNotBlank(msg) ? msg : BaseCodeEnum.SUCCESS.getMsg());
        view.setData(data);
        return view;
    }

    /**
     * 统一返回错误
     *
     */
    public static <T> View<T> error() {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.FAILED.getCode());
        view.setMsg(BaseCodeEnum.FAILED.getMsg());
        return view;
    }

    /**
     * 统一返回错误
     *
     * @param msg 错误描述，可以为空
     */
    public static <T> View<T> error(String msg) {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.FAILED.getCode());
        view.setMsg(StringUtils.isNotBlank(msg) ? msg : BaseCodeEnum.FAILED.getMsg());
        return view;
    }


    public static <T> View<T> error(Integer code, String msg) {
        View<T> view = new View<>();
        view.setCode(code != null ? code : BaseCodeEnum.FAILED.getCode());
        view.setMsg(StringUtils.isNotBlank(msg) ? msg : BaseCodeEnum.FAILED.getMsg());
        return view;
    }

    public static <T> View<T> error(String msg, T data) {
        View<T> view = new View<>();
        view.setCode(BaseCodeEnum.FAILED.getCode());
        view.setMsg(StringUtils.isNotBlank(msg) ? msg : BaseCodeEnum.FAILED.getMsg());
        view.setData(data);
        return view;
    }

    /**
     * 接口返回的view对象验证
     *
     * @param view 接口封装返回的对象
     * @return boolean
     */
    public static boolean verifyViewPort(View<Object> view) {
        return view != null && view.getData() != null && BaseCodeEnum.SUCCESS.getCode().equals(view.getCode());
    }


}
